package me.lovatcat.springboot.demo.spring;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @author acat on 2017-01-12 15:32
 */
@Aspect
@Component
public class WebLogAspect {

    private static final Logger LOG = LoggerFactory.getLogger(WebLogAspect.class);

    //切点， 每一个controller请求方法
    @Pointcut("execution(public * me.lovatcat.springboot.demo.web.controller..*.*(..))")
    public void webLog(){}

    //如果有多个aop切面时，可以通过@Order(i)来设置执行顺序，
    //@Before中先执行i小的切面，@AfterReturning中先执行i大的切面
    @Before("webLog()")
    public void req_enter_log(JoinPoint joinPoint) throws Throwable {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 记录下请求内容
        LOG.info("URL ==> {}, HTTP_METHOD ==> {}, IP ==> {}, CLASS_METHOD ==> {}.{}, ARGS ==> {}",
                request.getRequestURL().toString(),
                request.getMethod(),
                request.getRemoteAddr(),
                joinPoint.getSignature().getDeclaringTypeName(),
                joinPoint.getSignature().getName(),
                Arrays.toString(joinPoint.getArgs())
        );
    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        String returnStr = ret.toString();
        if(returnStr.length() <= 500){
            // 处理完请求，返回内容
            LOG.info("RESPONSE ==> {}" + ret);
        }else{
            LOG.info("RESPONSE ==> 响应成功");
        }
    }


}
